<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                                 |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//

namespace AuctionBack\Logic;

use AuctionCore\AntNest\Sms;
use AuctionCore\AntNest\UserCenter;
use AuctionCore\CarResource\CarModel;
use AuctionCore\ChangeCar\ChangeCar;
use AuctionCore\Common\PhpRedis;
use AuctionCore\Other\Address;
use AuctionCore\Other\MyCustomer;

class ClcwUserLogic extends BaseLogic
{
    protected $autoCheckFields = false;

    private $clcwUserModel;

    private $userExpertModel;

    private $userScoreModel;

    private $userExpModel;

    private $tradeLogModel;

    public function __construct()
    {
        $this->clcwUserModel = D('ClcwUser', 'Model');
        $this->userExpertModel = D('UserExpert', 'Model');
        $this->userScoreModel = D('UserScore', 'Model');
        $this->userExpModel = D('UserExp', 'Model');
        $this->tradeLogModel = D('TradeLog', 'Model');
    }

    /**
     * 车来车往用户列表
     *
     * @param int $page
     * @param int $size
     * @param     $params
     */
    public function getClcwUserList($page = 1, $size = 10, $params)
    {
        $map = [];
        if (intval($params['uid']) > 0) {
            $map['user_id'] = intval($params['uid']);
        }
        if (!empty($params['user_name'])) {
            $map['nick_name'] = ['like', "%" . trim($params['user_name']) . "%"];
        }
        if (!empty($params['real_name'])) {
            $map['real_name'] = ['like', "%" . trim($params['real_name']) . "%"];
        }

        if (!empty($params['phone'])) {
            $map['mobile'] = trim($params['phone']);
        }

        if ($params['level']) {
            switch ($params['level']) {
                case 1:
                    $map['user_exp'] = [['egt', 0], ['lt', 100]];
                    break;
                case 2:
                    $map['user_exp'] = [['egt', 101], ['lt', 1000]];
                    break;
                case 3:
                    $map['user_exp'] = [['egt', 1001], ['lt', 2000]];
                    break;
                case 4:
                    $map['user_exp'] = [['egt', 2001], ['lt', 5000]];
                    break;
                case 5:
                    $map['user_exp'] = [['egt', 5001], ['lt', 10000000]];
                    break;
                default:
                    break;

            }
        }

        if ($params['is_expert'] == 1) {
            $map['is_expert'] = ['eq', 1];
        } elseif ($params['is_expert'] == 2) {
            $map['is_expert'] = ['eq', 0];
        }

        if ($params['is_recommend_expert'] == 1) {
            $map['is_top'] = ['eq', 1];
        } elseif ($params['is_recommend_expert'] == 2) {
            $map['is_top'] = ['eq', 0];
        }

        //状态0删除,1启用,2禁用
        if (intval($params['status']) > 0) {
            $map['status'] = intval($params['status']);
        } else {
            $map['status'] = ['gt', 0];
        }
        //注册时间
        if ($params['start_time']) {
            $map['create_time'] = ['egt', strtotime($params['start_time'] . ' 00:00:00')];
        }
        if ($params['end_time']) {
            $map['create_time'] = ['elt', strtotime($params['end_time'] . ' 23:59:59')];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['create_time'] = [
                ['egt', strtotime($params['start_time'] . ' 00:00:00')],
                ['elt', strtotime($params['end_time'] . ' 23:59:59')]
            ];
        }
        $cols = 'user_id,nick_name,real_name,mobile,user_exp,is_expert,is_top,status,create_time';
        $order = 'create_time DESC';
        $total = $this->clcwUserModel->field($cols)
            ->where($map)->count();
        $list = $this->clcwUserModel->field($cols)
            ->where($map)
            ->page($page)
            ->limit($size)
            ->order($order)
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['is_expert_name'] = $v['is_expert'] == 1 ? '是' : '否';
            $list[$k]['is_top_expert'] = $v['is_top'] == 1 ? '是' : '否';
            $level = $this->getLevel($v['user_exp']);
            $list[$k]['user_level'] = $level['level_name'];
            $list[$k]['status_name'] = $v['status'] == 1 ? '正常' : '禁用';
            $list[$k]['create_time'] = date('Y-m-d H:i', $v['create_time']);
        }
        $result = [
            'list'  => $list,
            'total' => $total
        ];
        return $result;
    }

    /**
     * 车来车往用户详情
     *
     * @param $userId
     */
    public function getClcwUserInfo($userId)
    {
        $condition['user_id'] = ['eq', $userId];
        $cols = 'user_id,nick_name,avatar,real_name,mobile,user_exp,user_score,user_money,is_expert,
                 is_top,expert_brand,expert_category,status,create_time,change_expert_time,user_intro,change_level_time';
        $info = $this->clcwUserModel->field($cols)->where($condition)->find();
        $info['avatar'] = getFullUrl($info['avatar']);
        $info['is_expert_name'] = $info['is_expert'] == 1 ? '是' : '否';
        $level = $this->getLevel($info['user_exp']);
        $info['user_level'] = $level['level_name'];
        $info['change_level_time'] = date('Y-m-d H:i', $info['change_level_time']);
        $info['status_name'] = $info['status'] == 1 ? '正常' : '禁用';
        $info['create_time'] = date('Y-m-d H:i', $info['create_time']);
        if ($info['is_expert'] == 1) {
            $info['change_expert_time'] = date('Y年m月d日 H:i', $info['change_expert_time']);
            $expBrandArr = explode(',', $info['expert_brand']);
            $cm = new CarModel();
            foreach ($expBrandArr as $kc => $vc) {
                $brand = $cm->get_model_by_id($vc, 'mbrand');
                $brandName[$vc] = $brand['name'];
            }
            $info['good_brand'] = implode('、', $brandName);
            $expCategory = explode(',', $info['expert_category']);
            foreach ($expCategory as $kb => $vb) {
                $category = D('Question', 'Logic')->getQuestionCategory($vb);
                $categoryName[$kb] = $category['category_name'];
            }
            $info['good_category'] = implode('、', $categoryName);
            $info['expert_category_list'] = $categoryName;
            $info['expert_brand_list'] = $brandName;
        }
        return $info;
    }

    /**
     * 根据ID获取牛人用户信息
     * @param int $userId
     *
     * @return bool|mixed
     */
    public function getExpertUserInfoByUid($userId = 0)
    {
        if (empty($userId)) {
            return false;
        }
        $condition['user_id'] = $userId;
        $condition['is_expert'] = 1;
        $condition['status'] = 1;
        return $this->clcwUserModel->where($condition)->find();
    }

    /**
     * 根据用户ID获取用户信息
     *
     * @param int $uid
     */
    public function getUserInfoByUid($uid = 0)
    {
        if (empty($uid)) {
            return false;
        }
        return $this->clcwUserModel->where(['user_id' => $uid])->find();
    }

    /**
     * 根据手机号获取用户信息
     *
     * @param $mobile
     */
    public function getUserInfoByMobile($mobile)
    {
        if (empty($mobile)) {
            return false;
        }
        return $this->clcwUserModel->where(['mobile' => $mobile])->find();
    }

    /**
     * 根据昵称获得用户ID
     *
     * @param $nick_name
     */
    public function getUserIdByNickName($nick_name)
    {
        if (empty($nick_name)) {
            return false;
        }
        return $this->clcwUserModel->where(['nick_name' => $nick_name])->getField('user_id');
    }

    /**
     * 获取用户成长值列表
     *
     * @param int   $page
     * @param int   $size
     * @param array $params
     */
    public function getGrowthList($page = 1, $size = 10, $params = [])
    {
        $map = [];
        if ($params['uid'] > 0) {
            $map['user_id'] = ['eq', $params['uid']];
        }
        if ($params['start_time']) {
            $map['create_time'] = ['egt', strtotime($params['start_time'] . ' 00:00:00')];
        }
        if ($params['end_time']) {
            $map['create_time'] = ['egt', strtotime($params['end_time'] . ' 23:59:59')];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['create_time'] = [
                ['egt', strtotime($params['start_time'] . ' 00:00:00')],
                ['elt', strtotime($params['end_time'] . ' 23:59:59')]
            ];
        }
        $cols = "exp_type,action_exp,after_exp,remark,create_time";
        $order = "id DESC";
        $total = $this->userExpModel->where($map)->count();
        $list = $this->userExpModel->field($cols)
            ->where($map)
            ->limit($size)
            ->page($page)
            ->order($order)
            ->select();
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $list[$k]['exp_group_name'] = C('EXP_TYPE')[$v['exp_type']];
                $list[$k]['exp_name'] = $v['remark'];
                $list[$k]['create_time'] = date("Y年m月d日 H:i", $v['create_time']);
                $list[$k]['action_exp'] = $this->getFormatExp($v['exp_type'], $v['action_exp']);
            }
        }
        $result = [
            'list'  => $list,
            'total' => $total
        ];
        return $result;
    }

    /**
     * @param $exp_type   经验值类型
     * @param $action_exp 经验值
     */
    private function getFormatExp($exp_type, $action_exp)
    {
        $exp = C('EXP')[$exp_type];
        if ($exp['sign'] > 0) {
            $format_exp = "+" . $exp['sign'] * $action_exp;
        } else {
            $format_exp = $exp['sign'] * $action_exp;
        }
        return $format_exp;
    }


    /**
     * 获取用户成长值列表
     *
     * @param int   $page
     * @param int   $size
     * @param array $params
     */
    public function getScoreList($page = 1, $size = 10, $params = [])
    {
        $map = [];
        $map['action_score'] = ['neq', 0];
        if ($params['uid'] > 0) {
            $map['user_id'] = ['eq', $params['uid']];
        }
        if ($params['start_time']) {
            $map['create_time'] = ['egt', strtotime($params['start_time'] . ' 00:00:00')];
        }
        if ($params['end_time']) {
            $map['create_time'] = ['egt', strtotime($params['end_time'] . ' 23:59:59')];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['create_time'] = [
                ['egt', strtotime($params['start_time'] . ' 00:00:00')],
                ['elt', strtotime($params['end_time'] . ' 23:59:59')]
            ];
        }
        $cols = "score_type,action_score,after_score,remark,create_time";
        $order = "id DESC";
        $total = $this->userScoreModel->where($map)->count();
        $list = $this->userScoreModel->field($cols)
            ->where($map)
            ->limit($size)
            ->page($page)
            ->order($order)
            ->select();
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $list[$k]['score_group_name'] = C('SCORE_TYPE')[$v['score_type']];
                $list[$k]['score_name'] = $v['remark'];
                $list[$k]['action_score'] = $this->getFormatScore($v['score_type'], $v['action_score']);
                $list[$k]['create_time'] = date("Y年m月d日 H:i", $v['create_time']);
            }
        }
        $result = [
            'list'  => $list,
            'total' => $total
        ];
        return $result;
    }

    /**
     * 获取对应类型积分值
     *
     * @param $score_type   积分类型
     * @param $action_score 发生积分值
     *
     * @return string
     */
    private function getFormatScore($score_type, $action_score)
    {
        $score = C('SCORE')[$score_type];
        if ($score['sign'] > 0) {
            $format_score = "+" . $score['sign'] * $action_score;
        } else {
            $format_score = $score['sign'] * $action_score;
        }
        return $format_score;
    }

    /**
     * 获取钱包列表
     *
     * @param int   $page
     * @param int   $size
     * @param array $params
     */
    public function getWalletList($page = 1, $size = 10, $params = [])
    {
        $map = [];
        if ($params['uid'] > 0) {
            $map['user_id'] = ['eq', $params['uid']];
        }
        if ($params['start_time']) {
            $map['create_time'] = ['egt', strtotime($params['start_time'] . ' 00:00:00')];
        }
        if ($params['end_time']) {
            $map['create_time'] = ['egt', strtotime($params['end_time'] . ' 23:59:59')];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['create_time'] = [
                ['egt', strtotime($params['start_time'] . ' 00:00:00')],
                ['elt', strtotime($params['end_time'] . ' 23:59:59')]
            ];
        }
        $cols = "type,action_amount,after_amount,remark,create_time";
        $order = "id DESC";
        $total = $this->tradeLogModel->where($map)->count();
        $list = $this->tradeLogModel->field($cols)
            ->where($map)
            ->limit($size)
            ->page($page)
            ->order($order)
            ->select();
        if (!empty($list)) {
            $sign = C('TRADE_SIGN');
            foreach ($list as $k => $v) {
                $list[$k]['wallet_name'] = C('USER_MONEY')[$v['type']];
                $list[$k]['create_time'] = date("Y年m月d日 H:i", $v['create_time']);

                if ($sign[$v['type']]) {
                    $list[$k]['action_amount'] = $sign[$v['type']] . $v['action_amount'];
                } else {
                    $list[$k]['action_amount'] = $v['action_amount'];
                }
            }
        }
        $result = [
            'list'  => $list,
            'total' => $total
        ];
        return $result;
    }

    /**
     * 获得用户爱车信息
     *
     * @param $userId
     */
    public function getClcwUserCar($userId)
    {
        if (empty($userId)) {
            return false;
        }
        $condition['uid'] = ['eq', $userId];
        $condition['status'] = ['eq', 1];
        $cols = 'city_code,plate_prefix,plate_suffix,engine_number,frame_number';
        $list = M('UserCar', 'clcw_', 'DB_CLCW')->field($cols)->where($condition)->select();
        if (!empty($list)) {
            $addr = new Address();
            foreach ($list as $k => $v) {
                $locationArea = $addr->get_name_by_code($v['city_code']);
                $list[$k]['location_area'] = $locationArea;
                $list[$k]['plate_number'] = C('PLATE_PREFIX')[$v['plate_prefix']] . $v['plate_suffix'];
            }
        }
        return $list;
    }

    /**
     * 更新用户设置为牛人信息
     *
     * @param array $data
     */
    public function updateUserInfo($data = [])
    {
        if (empty($data['user_id'])) {
            return false;
        }
        $data['update_time'] = time();
        if ($data['is_expert'] == 1) {
            $data['is_expert'] = 1;
        }
        if ($data['is_expert'] == 0) {
            $this->userExpertModel->where(['user_id' => $data['user_id']])->delete();
        }
        if (!empty($data['expert_brand'])) {
            $expert_brand_arr = explode(',', $data['expert_brand']);
            foreach ($expert_brand_arr as $k => $v) {
                $this->userExpertModel->add([
                    'user_id'  => $data['user_id'],
                    'brand_id' => $v
                ]);
            }
        }
        return $this->clcwUserModel->save($data);
    }

    /**
     * 更新个人账号编辑信息
     *
     * @param array $data
     */
    public function updateClcwUserEditInfo($data = [])
    {
        if (empty($data['user_id'])) {
            return false;
        }
        if ($data['is_expert'] == 1) {
            $brandArr = explode(',', $data['expert_brand']);
            if (!empty($brandArr)) {
                $condition = [];
                $condition['user_id'] = ['eq', $data['user_id']];
                $condition['brand_id'] = ['not in', $brandArr];
                $abc = $this->userExpertModel->where($condition)->delete();
                foreach ($brandArr as $vb) {
                    $isExist = $this->userExpertModel->where(
                        [
                            'user_id'  => $data['user_id'],
                            'brand_id' => $vb
                        ]
                    )->count();
                    if (!$isExist) {
                        $this->userExpertModel->add(
                            [
                                'user_id'  => $data['user_id'],
                                'brand_id' => $vb
                            ]
                        );
                    }
                }
            }
        } else {
            $data['is_top'] = 0;
            $data['expert_brand'] = '';
            $data['user_intro'] = '';
            $this->userExpertModel->where(['user_id' => $data['user_id']])->delete();
        }
        $data['update_time'] = NOW_TIME;
        return $this->clcwUserModel->save($data);
    }

    /**
     * 启用帐号
     *
     * @param array $user
     * @param int   $userId
     *
     * @return boolean
     */
    public function enableClcwUser($user = [], $userId)
    {
        //开启事务
        M()->startTrans();
        $userRes = $this->clcwUserModel->where(['user_id' => $userId])->setField('status', 1);
        $uc = new UserCenter();
        $ucRes = $uc->active($user, 1);
        if (!$userRes || !$ucRes) {
            M()->rollback();
            return false;
        }
        M()->commit();
        return true;
    }

    /**
     * 禁用帐号
     *
     * @param array $user
     * @param int   $userId
     *
     * @return  boolean
     */
    public function disableClcwUser($user, $userId)
    {
        M()->startTrans();
        $userRes = $this->clcwUserModel->where(['user_id' => $userId])->setField('status', 2);
        $uc = new UserCenter();
        $ucRes = $uc->inactive($user, 1);
        if (!$userRes || !$ucRes) {
            M()->rollback();
            return false;
        }
        M()->commit();
        return true;
    }

    /**
     * 变更用户积分
     *
     * @param        $userId
     * @param        $score_type
     * @param string $remark
     * @param int    $score
     */
    public function change_user_score($userId, $score_type, $remark = '', $score = 0)
    {
        $condition['user_id'] = $userId;

        $userInfo = $this->clcwUserModel->where($condition)->find();

        //修改用户积分
        $config = C('SCORE')[$score_type];
        if (!$config || !$userId) {
            return false;
        }
        $time = time();

        if ($config['value'] > 0) {
            $score = $config['sign'] * $config['value'];
        } else {
            $score = $config['sign'] * $score;
        }
        $afterScore = $userInfo['user_score'] + $score;

        $updateData = [
            'user_score'  => $afterScore,
            'update_time' => $time,
        ];

        M('', 'clcw_', 'DB_CLCW')->startTrans();
        $res1 = $this->clcwUserModel->where($condition)->save($updateData);
        //添加用户积分历史
        $insertData = [
            'user_id'      => $userId,
            'score_type'   => $score_type,
            'before_score' => $userInfo['user_score'],
            'action_score' => $score,
            'after_score'  => $afterScore,
            'remark'       => $remark,
            'create_time'  => $time
        ];
        $res2 = $this->userScoreModel->add($insertData);
        if ($res1 && $res2) {
            M('', 'clcw_', 'DB_CLCW')->commit();
            return true;
        } else {
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
    }

    /**
     * 变更用户经验
     *
     * @param        $userId
     * @param        $exp_type
     * @param string $remark
     * @param int    $exp
     */
    public function change_user_exp($userId, $exp_type, $remark = '', $exp = 0)
    {
        $condition['user_id'] = $userId;

        $userInfo = $this->clcwUserModel->where($condition)->find();

        //修改用户积分
        $config = C('EXP')[$exp_type];

        if (!$config || !$userId) {
            return false;
        }

        $time = time();

        if ($config['value'] > 0) {
            $exp = $config['sign'] * $config['value'];
        } else {
            $exp = $config['sign'] * $exp;
        }

        $afterExp = $userInfo['user_exp'] + $exp;

        $updateData = [
            'user_exp'    => $afterExp,
            'update_time' => $time,
        ];
        //如果等级有变动更改用户等级变更时间
        $nowLevel = $this->getLevel($userInfo['user_exp']);
        $afterLevel = $this->getLevel($afterExp);
        if ($nowLevel != $afterLevel) {
            $updateData['change_level_time'] = $time;
        }
        M('', 'clcw_', 'DB_CLCW')->startTrans();
        $res1 = $this->clcwUserModel->where($condition)->save($updateData);
        //添加用户成长值历史
        $insertData = [
            'user_id'     => $userId,
            'exp_type'    => $exp_type,
            'before_exp'  => $userInfo['user_exp'],
            'action_exp'  => $exp,
            'after_exp'   => $afterExp,
            'remark'      => $remark,
            'create_time' => $time
        ];
        $res2 = $this->userExpModel->add($insertData);

        if ($res1 && $res2) {
            M('', 'clcw_', 'DB_CLCW')->commit();
            return true;
        } else {
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
    }

    /**
     * 变更用户金钱
     *
     * @param int    $userId
     * @param        $moneyType
     * @param string $remark
     * @param int    $money
     */
    public function changeUserMoney($userId = 0, $moneyType, $remark = '', $money = 0)
    {
        $condition['user_id'] = $userId;

        $userInfo = $this->clcwUserModel->where($condition)->find();

        //修改用户金钱
        $config = C('USER_MONEY')[$moneyType];

        if (!$config || !$userId) {
            return false;
        }
        $time = time();
        $afterMoney = $userInfo['user_money'] + $money;
        $updateData = [
            'user_money'  => $afterMoney,
            'update_time' => $time
        ];
        M('', 'clcw_', 'DB_CLCW')->startTrans();
        $res1 = $this->clcwUserModel->where($condition)->save($updateData);
        //添加用户积分历史
        $insertData = [
            'user_id'       => $userId,
            'type'          => $moneyType,
            'before_amount' => $userInfo['user_money'],
            'action_amount' => $money,
            'after_amount'  => $afterMoney,
            'remark'        => $remark,
            'create_time'   => $time
        ];
        $res2 = $this->tradeLogModel->add($insertData);
        if ($res1 && $res2) {
            M('', 'clcw_', 'DB_CLCW')->commit();
            return true;
        } else {
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
    }

    /**
     * 增加用户回答数
     *
     * @param int $userId
     */
    public function incUserQuestionNum($userId = 0)
    {
        if (empty($userId)) {
            return false;
        }
        $condition['user_id'] = $userId;
        return $this->clcwUserModel->where($condition)->setInc('question_num');
    }

    /**
     * 减少用户回答数
     *
     * @param int $userId
     */
    public function decUserQuestionNum($userId = 0)
    {
        if (empty($userId)) {
            return false;
        }
        $condition['user_id'] = $userId;
        return $this->clcwUserModel->where($condition)->setDec('question_num');
    }

    /**
     * 增加用户回答数
     *
     * @param int $userId
     */
    public function incUserAnswerNum($userId = 0)
    {
        if (empty($userId)) {
            return false;
        }
        $condition['user_id'] = $userId;
        return $this->clcwUserModel->where($condition)->setInc('answer_num');
    }

    /**
     * 减少用户回答数
     *
     * @param int $userId
     */
    public function dec_user_answer_num($userId = 0)
    {
        if (empty($userId)) {
            return false;
        }
        $condition['user_id'] = $userId;
        return $this->clcwUserModel->where($condition)->setDec('answer_num');
    }

    /**
     * 增加用户采纳数
     *
     * @param int $userId
     *
     * @return bool
     */
    public function incUserAcceptNum($userId = 0)
    {
        if (empty($userId)) {
            return false;
        }
        $condition['user_id'] = $userId;
        return $this->clcwUserModel->where($condition)->setInc('accept_num');
    }

    /**
     * 减少用户采纳数
     *
     * @param int $userId
     *
     * @return bool
     */
    public function decUserAcceptNum($userId = 0)
    {
        if (empty($userId)) {
            return false;
        }
        $condition['user_id'] = $userId;
        return $this->clcwUserModel->where($condition)->setDec('accept_num');
    }

    /**
     * 获取经验所属类型
     *
     * @param int $exp_type
     *
     * @return array
     */
    private function getExpGroup($exp_type = 1)
    {
        $config = C('USER_EXP_GROUP');
        foreach ($config as $k => $v) {
            $needExp = explode('-', $k);
            if ($exp_type >= $needExp[0] && $exp_type <= $needExp[1]) {
                return [
                    'exp_group' => $v
                ];
            }
        }
    }

    /**
     * 获取积分所属类型
     *
     * @param int $scoreType
     *
     * @return array
     */
    private function getScoreGroup($scoreType = 1)
    {
        $config = C('USER_SCORE_GROUP');
        foreach ($config as $k => $v) {
            $needExp = explode('-', $k);
            if ($scoreType >= $needExp[0] && $scoreType <= $needExp[1]) {
                return [
                    'score_group' => $v
                ];
            }
        }
    }

    /**
     * 获取用户等级
     *
     * @param $exp
     *
     * @return array
     */
    private function getLevel($exp)
    {
        $config = C('USER_LEVEL');
        foreach ($config as $k => $v) {
            $needExp = explode('-', $k);
            if ($exp >= $needExp[0] && $exp <= $needExp[1]) {
                return [
                    'level_lower' => $needExp[0],
                    'level_upper' => $needExp[1],
                    'level_name'  => $v
                ];
            }
        }
    }

    /**
     * 创建车来车往用户
     *
     * @param $ownerId
     * @param $phone
     *
     * @return mixed
     */
    public function createClcwUser($ownerId, $phone)
    {
        $uc = new UserCenter();
        $user = $uc->info($phone, 1, 2);
        $data = [];
        $sms = new Sms();
        if (!empty($user)) {
            $userId = $user['account_id'];
            $data['owner_id'] = $ownerId;
            $data['uid'] = $userId;
            //短信通知车主
            $sms->notify(17, $phone, []);
        } else {
            $userId = $this->createOwnerUser($phone, md5('123456'));
            $data['owner_id'] = $ownerId;
            $data['uid'] = $userId;
            //如果创建用户A是B的客户，则创建经纪人帐号A是B的下级
            $myCustomer = new MyCustomer();
            $customer = $myCustomer->getCustomer(['owner_id' => $ownerId]);
            if (!empty($customer)) {
                $agent = D('Agent', 'Logic')->getDetailByUid($customer['uid']);
                D('Agent', 'Logic')->create($userId, $customer['phone'], $agent['aid']);
            } else {
                D('Agent', 'Logic')->create($userId, $phone, 0);
            }
            //创建车主帐号，短信通知车主帐号密码
            $sms->notify(16, $phone, ['mob' => $phone, 'pwd' => '123456']);
        }
        //卖车检测成功送积分及经验值
        if ($userId) {
            $redis = new PhpRedis(0);
            $keyName = getRedisKeyByCode('REDIS_KEY', '100000');
            $bizData = [
                'bizContent' =>
                    [
                        'scoreType' => 11,
                        'score'     => 200,
                        'remark'    => '',
                        'userId'    => (int)$userId
                    ],
                'bizType'    => 5
            ];
            $redis->lpush($keyName, json_encode($bizData));
            $bizData = [
                'bizContent' =>
                    [
                        'expType' => 11,
                        'exp'     => 20,
                        'remark'  => '',
                        'userId'  => (int)$userId
                    ],
                'bizType'    => 6
            ];
            $redis->lpush($keyName, json_encode($bizData));
        }
        return M('car_owner')->save($data);
    }

    /**
     * 创建用户
     *
     * @param $mobile
     * @param $password
     *
     * @return bool
     */
    public function createOwnerUser($mobile, $password)
    {
        if (empty($mobile) || empty($password)) {
            return false;
        }
        $uc = new UserCenter();
        $data = $uc->register($mobile, $password);
        $userId = $data['account_id'];
        if ($userId) {
            $user = [
                'user_id' => $userId,
                'mobile'  => $mobile,
                'status'  => 1,
            ];
            $this->insertUserExInfo($user);
            $this->insertUserStatistics($userId);
            $this->createRelationWithChangeCar($user['user_id'], $user['mobile']);
            $this->createRelationWithCarOwner($user['user_id'], $user['mobile']);
        }
        return $userId;
    }

    /**
     * 新建用户信息
     *
     * @param $user
     *
     * @return bool|mixed
     */
    private function insertUserExInfo($user)
    {
        if (empty($user['user_id'])) {
            return false;
        }
        $user['change_level_time'] = NOW_TIME;
        $user['create_time'] = NOW_TIME;
        $data = $this->clcwUserModel->create($user);
        if ($data) {
            return $this->clcwUserModel->add($data);
        } else {
            return false;
        }
    }

    /**
     * 插入用户统计
     *
     * @param int $userId
     */
    private function insertUserStatistics($userId = 0)
    {
        if (empty($userId)) {
            return false;
        }
        $userStatistics = new UserStatisticsLogic();
        return $userStatistics->addUserStatistics(['user_id' => $userId, 'last_act_time' => NOW_TIME]);
    }

    /**
     * 注册时用户与换车信息建立关联关系
     *
     * @param $userId
     * @param $mobile
     */
    private function createRelationWithChangeCar($userId = 0, $mobile = 0)
    {
        if (empty($userId) || empty($mobile)) {
            return false;
        }
        $changeCar = new ChangeCar();
        $changeCarInfo = $changeCar->getChangeCarByMobile($mobile);
        if (empty($changeCarInfo)) {
            $changeCarData['id'] = $changeCarInfo['id'];
            $changeCarData['uid'] = $userId;
            return $changeCar->saveChangeCarInfo($changeCarData);
        }
        return false;
    }

    /**
     * 注册时用户与车主线索信息建立关联关系
     *
     * @param int $userId
     * @param int $mobile
     */
    private function createRelationWithCarOwner($userId = 0, $mobile = 0)
    {
        if (empty($userId) || empty($mobile)) {
            return false;
        }
        $carOwner = D('CarOwner', 'Logic')->getCarOwnerInfoByPhone($mobile);
        if ($carOwner) {
            $carOwnerData['owner_id'] = $carOwner['owner_id'];
            $carOwnerData['uid'] = $userId;
            return D('CarOwner', 'Logic')->updateCarOwnerInfo($carOwnerData);
        } else {
            return false;
        }
    }


    /**
     * 获取用户数据统计列表
     *
     * @param int $page
     * @param int $size
     * @param     $params
     */
    public function getUserStatisticsList($page = 1, $size = 10, $params)
    {
        $map = [];
        if ($params['user_id']) {
            $map['u.user_id'] = ['EQ', $params['user_id']];
        }
        if (!empty($params['user_name'])) {
            $map['u.nick_name'] = ['like', "%" . trim($params['user_name']) . "%"];
        }
        if (!empty($params['real_name'])) {
            $map['u.real_name'] = ['like', "%" . trim($params['real_name']) . "%"];
        }

        if (!empty($params['phone'])) {
            $map['u.mobile'] = trim($params['phone']);
        }

        if ($params['level']) {
            switch ($params['level']) {
                case 1:
                    $map['u.user_exp'] = [['egt', 0], ['lt', 100]];
                    break;
                case 2:
                    $map['u.user_exp'] = [['egt', 101], ['lt', 1000]];
                    break;
                case 3:
                    $map['u.user_exp'] = [['egt', 1001], ['lt', 2000]];
                    break;
                case 4:
                    $map['u.user_exp'] = [['egt', 2001], ['lt', 5000]];
                    break;
                case 5:
                    $map['u.user_exp'] = [['egt', 5001], ['lt', 10000000]];
                    break;
                default:
                    break;

            }
        }

        if ($params['is_expert'] == 1) {
            $map['u.is_expert'] = ['eq', 1];
        } elseif ($params['is_expert'] == 2) {
            $map['u.is_expert'] = ['eq', 0];
        }

        //状态0删除,1启用,2禁用
        if (intval($params['status']) > 0) {
            $map['u.status'] = intval($params['status']);
        } else {
            $map['u.status'] = ['gt', 0];
        }
        //注册时间
        if ($params['start_time']) {
            $map['create_time'] = ['egt', strtotime($params['start_time'] . ' 00:00:00')];
        }
        if ($params['end_time']) {
            $map['create_time'] = ['elt', strtotime($params['end_time'] . ' 23:59:59')];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['create_time'] = [
                ['egt', strtotime($params['start_time'] . ' 00:00:00')],
                ['elt', strtotime($params['end_time'] . ' 23:59:59')]
            ];
        }
        switch ($params['sort']) {
            case 1:
                $order = 'u.user_score DESC';
                break;
            case 2:
                $order = 'us.exchange_score DESC';
                break;
            case 3:
                $order = 'u.user_exp DESC';
                break;
            case 4:
                $order = 'us.sign_num DESC';
                break;
            case 5:
                $order = 'us.common_question_num DESC';
                break;
            case 6:
                $order = 'us.pay_question_num DESC';
                break;
            case 7:
                $order = 'u.answer_num DESC';
                break;
            case 8:
                $order = 'us.answer_income DESC';
                break;
            case 9:
                $order = 'u.user_money DESC';
                break;
            case 10:
                $order = 'us.user_car_num DESC';
                break;
            case 11:
                $order = 'us.oil_amount DESC';
                break;
            case 12:
                $order = 'us.oil_card_num DESC';
                break;
            default:
                $order = 'u.create_time DESC';
                break;
        }
        $cols = 'u.user_id,u.nick_name,u.real_name,u.mobile,u.user_score,u.user_exp,u.user_money,u.answer_num
        ,u.is_expert,u.status,u.create_time,us.*';

        $prefix = C('DB_CLCW')['DB_PREFIX'];
        $total = $this->clcwUserModel->alias('u')
            ->join($prefix . 'user_statistics as us ON us.user_id=u.user_id')
            ->where($map)->count();
        $list = $this->clcwUserModel->alias('u')->field($cols)
            ->join($prefix . 'user_statistics as us ON us.user_id=u.user_id')
            ->where($map)
            ->page($page)
            ->limit($size)
            ->order($order)
            ->select();
        if (!empty($list)) {
            $clcwUserSignLogic = new ClcwUserSignLogic();
            $clcwCarOmenLogic = new ClcwCarOmenLogic();
            $oilPayOrderLogic = new OilPayOrderLogic();
            foreach ($list as $k => $v) {
                $list[$k]['is_expert_name'] = $v['is_expert'] == 1 ? '是' : '否';
                $level = $this->getLevel($v['user_exp']);
                $list[$k]['user_level'] = $level['level_name'];
                $list[$k]['status_name'] = $v['status'] == 1 ? '启用' : '禁用';
                $list[$k]['create_time'] = date("Y-m-d H:i:s", $v['create_time']);
                $list[$k]['last_act_time'] = date("Y-m-d H:i:s", $v['last_act_time']);
                //用户签到记录
                $list[$k]['user_sign_list'] = $clcwUserSignLogic->getUserSignListByUid($v['user_id']);
                $list[$k]['car_omen_list'] = $clcwCarOmenLogic->getCarOmenListByUid($v['user_id']);
                $list[$k]['user_car_list'] = $this->getClcwUserCarByUid($v['user_id']);
                $list[$k]['oil_order_list'] = $oilPayOrderLogic->getOilOrderListByUid($v['user_id']);
            }
        }
        $result = [
            'list'  => $list,
            'total' => $total
        ];
        return $result;
    }

    /**
     * 获取用户爱车记录
     *
     * @param int $userId
     *
     * @return bool|mixed
     */
    private function getClcwUserCarByUid($userId = 0)
    {
        if (empty($userId)) {
            return false;
        }
        $condition['uid'] = ['eq', $userId];
        $cols = 'city_code,plate_prefix,plate_suffix,engine_number,frame_number,status';
        $list = M('UserCar', 'clcw_', 'DB_CLCW')->field($cols)->where($condition)->select();
        if (!empty($list)) {
            $addr = new Address();
            $i = 1;
            foreach ($list as $k => $v) {
                $list[$k]['sort'] = $i;
                $locationArea = $addr->get_name_by_code($v['city_code']);
                $list[$k]['location_area'] = $locationArea;
                $list[$k]['plate_number'] = C('PLATE_PREFIX')[$v['plate_prefix']] . $v['plate_suffix'];
                $list[$k]['status_name'] = $v['status'] == 1 ? '未删除' : '已删除';
                $i++;
            }
        }
        return $list;
    }
}